package com.jinsi.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.jinsi.pojo.ScStudent;
import com.jinsi.service.ScStuService;
import com.jinsi.service.impl.ScStuServiceImpl;
import com.jinsi.utils.StuIdUtils;

import java.util.ArrayList;
import java.util.List;

public class StuListener implements ReadListener<ScStudent> {

    private static final int BATCH_COUNT = 100;


    private List<ScStudent> cachedDataList = new ArrayList<>(BATCH_COUNT);

    private ScStuService stuService;

    private StuListener(){
        stuService  = new ScStuServiceImpl();
    }

    public StuListener(ScStuService service){
        this.stuService = service;
    }



    @Override
    public void invoke(ScStudent data, AnalysisContext context) {
        data.setStudentId(StuIdUtils.getStudentId());
        System.out.println(data);

        cachedDataList.add(data);

        if (cachedDataList.size() >= BATCH_COUNT){
            saveData();

            cachedDataList = new ArrayList<>();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    private void saveData(){
        stuService.save(cachedDataList);
    }

}
